var express = require('express');
var router = express.Router();

var MongoClient = require('mongodb').MongoClient;
var DB_CONN_STR = "mongodb://localhost:27017/douban";

var async = require('async');

var multiparty = require('multiparty');
var fs = require('fs');

/* GET home page. */
router.get('/', function(req, res, next) {
    function findData(db, cb) {
        async.parallel([ //并行无关联
            function(cb) {
                var conn = db.collection('in_theaters');
                conn.find().toArray(function(err, result) {
                    if (err) {
                        return;
                    } else {
                        cb(null, result);
                    }
                });
            },
            function(cb) {
                var conn = db.collection('coming_soon');
                conn.find().toArray(function(err, result) {
                    if (err) {
                        return;
                    } else {
                        cb(null, result);
                    }
                });
            },
            function(cb) {
                var conn = db.collection('top250');
                conn.find().toArray(function(err, result) {
                    if (err) {
                        return;
                    } else {
                        cb(null, result);
                    }
                });
            },
            function(cb) {
                var conn = db.collection('us_box');
                conn.find().toArray(function(err, result) {
                    if (err) {
                        return;
                    } else {
                        cb(null, result);
                    }
                });
            }
        ], function(err, result) {
            cb(null, result);
        })

    };
    MongoClient.connect(DB_CONN_STR, function(err, db) {
        if (err) {
            console.log(err);
        } else {
            findData(db, function(err, result) {
                // console.log(result);
                res.render('index', { data: result, username: req.session.username });
                db.close();
            })
        }
    })
});

router.get('/login', function(req, res, next) {
    res.render('login', { error: req.session.error }); // render 渲染
});

// register
router.get('/register', function(req, res, next) {
    res.render('register', { repeat: req.session.repeat }); // render 渲染
});

// logout
router.get('/logout', function(req, res, next) {
    req.session.destroy(function(err) {
        res.redirect('/')
    })
});

router.get('/details', function(req, res, next) { //跳转详情页
    // res.send('id'+req.query.id);
    var pageNo = req.query.pageNo,
        pageNo = pageNo ? pageNo : 1,
        pageSize = 5,
        count = 0,
        totalPages = 0;

    MongoClient.connect(DB_CONN_STR, function(err, db) {
        if (err) {
            return;
        } else {
            findData(db, function(err, result) {
                for (var i = 0; i < result.length; i++) {
                    if (result[i].length == 0) {
                        continue;
                    } else {
                        if (i < 4) {
                            var data = result[i][0];
                            if (i == 3) {
                                data = result[i][0].subject;
                            }
                        } else {
                            var comment = result[i];
                        }
                    }
                }
                console.log(comment);
                res.render('details', {
                    det: data,
                    pageNo: pageNo,
                    totalPages: totalPages,
                    list: comment,
                    count: count
                });
                db.close();
            })
        };
    });

    function findData(db, cb) {
        async.parallel([
            function(cb) {
                var conn = db.collection('in_theaters');
                var data = { id: req.query.id };
                conn.find(data).toArray(function(err, result) {
                    if (err) {
                        return;
                    } else {
                        cb(null, result);
                    }
                })
            },
            function(cb) {
                var conn = db.collection('coming_soon');
                var data = { id: req.query.id };
                conn.find(data).toArray(function(err, result) {
                    if (err) {
                        return;
                    } else {
                        cb(null, result);
                    }
                })
            },
            function(cb) {
                var conn = db.collection('top250');
                var data = { id: req.query.id };
                conn.find(data).toArray(function(err, result) {
                    if (err) {
                        return;
                    } else {
                        cb(null, result);
                    }
                })
            },
            function(cb) {
                var conn = db.collection('us_box');
                conn.find({ 'subject.id': req.query.id }).toArray(function(err, result) {
                    if (err) {
                        console.log(err);
                        return;

                    } else {
                        cb(null, result);
                    }
                })
            },
            function(cb) {

                var conn = db.collection('comment');
                async.parallel([
                    function(cb) {
                        conn.find().toArray(function(err, result) {
                            if (err) {
                                return;
                            } else {
                                totalPages = Math.ceil(result.length / pageSize);
                                count = result.length;
                                cb(null, result);
                            }
                        })
                    },
                    function(cb) {
                        conn.find().sort({ _id: -1 }).skip((pageNo - 1) * pageSize).limit(pageSize).toArray(function(err, result) {
                            if (err) {
                                return;
                            } else {
                                cb(null, result);
                            }
                        })
                    }
                ], function(err, result) {
                    cb(null, result[1]);
                });
            }
        ], function(err, result) {
            cb(err, result);
        })
    }
});

//图片上传
router.post('/uploadImg', function(req, res, next) {

    var form = new multiparty.Form();
    form.encoding = 'utf-8';
    form.uploadDir = './uploadtmp';
    form.maxFilesSize = 100 * 1024;

    //表单解析
    form.parse(req, function(err, fields, files) {
        // 取files对象里面的一些信息内容
        // 设置了一个目录上传的新的文件名结构以及路径地址
        // console.log(files);
        var uploadurl = '/images/upload/';
        var file = files['filedata'];


        var originalFilename = file[0].originalFilename;
        var tmpPath = file[0].path;

        var timestamp = new Date().getTime();
        uploadurl += timestamp + originalFilename;
        var newPath = './public' + uploadurl;
        // public/images/upload/12123123213logo.jpg


        // 对原文件内容进行一个流文件信息的读取
        var fileReadStream = fs.createReadStream(tmpPath);
        var fileWriteStream = fs.createWriteStream(newPath);
        fileReadStream.pipe(fileWriteStream);
        fileWriteStream.on('close', function() {
            fs.unlinkSync(tmpPath);
            //  {"err":"","msg":"200906030521128703.gif"}
            res.send('{"err":"","msg":"' + uploadurl + '"}')
        })
    })

})



module.exports = router;